import os
import time
import pyautogui
from Utils import *


# 调用在执行动作后暂停的秒数，只能在执行一些pyautogui动作后才能使用，建议用time.sleep
# pyautogui.PAUSE = 3
# 启用自动防故障功能，左上角的坐标为（0，0），将鼠标移到屏幕的左上角，来抛出failSafeException异常
# pyautogui.FAILSAFE = True


class PerfDogUtils(object):
    def __init__(self):
        pyautogui.PAUSE = 2
        pyautogui.FAILSAFE = True
        pass

    def close_warning(self):
        """
        某条出现异常时, 需手动关闭弹出的警告框(后续改为装饰器方式实现)

        :return:
        """
        # warning = pyautogui.locateOnScreen(os.getcwd() + '\Image\warning.png')
        warning_close = pyautogui.locateOnScreen(os.getcwd() + '\Image\warning_close.png')
        if warning_close is not None:
            box_x, box_y = pyautogui.center(warning_close)
            pyautogui.click(x=box_x, y=box_y)

    def click_img(self, img_name):
        """
        点击指定图片所在位置的中心点

        :param img_name: 图片名称
        :return:
        """
        try:
            box = pyautogui.locateOnScreen(os.getcwd() + '\\Image\\' + img_name + '.png')
            box_x, box_y = pyautogui.center(box)
            pyautogui.click(x=box_x, y=box_y)
        except Exception as e:
            raise e
        finally:
            # self.close_warning()
            pass

    def click_app(self, app_name):
        """
        在左侧下拉列表选择应用

        :param app_name: 简写的应用的包名, 如`音乐`就是`music`
        :return:
        """
        try:
            flag = True
            while flag:
                box = pyautogui.locateOnScreen(os.getcwd() + '\\Image\\' + app_name + '.png')

                if box is None:
                    # 点击滑动点
                    self.click_img('slide_point')
                else:
                    box_x, box_y = pyautogui.center(box)
                    pyautogui.click(x=box_x, y=box_y)
                    flag = False
        except Exception as e:
            raise e
        finally:
            # self.close_warning()
            pass

    def start_test(self, app_name):
        """
        开始测试

        :param app_name: 简写的应用的包名, 如`音乐`就是`music`
        :return:
        """
        time.sleep(5)

        # 点击`选择测试应用`
        self.click_img('select_test_app')

        # 点击`指定应用`
        self.app_name = app_name
        self.click_app(self.app_name)
        time.sleep(3)

        # 点击开始测试
        self.click_img('start_test_icon')
        # 向左移动鼠标, 100个像素
        pyautogui.moveRel(-100, 0, duration=0.25)

    def stop_test(self):
        """
        停止测试

        :return:
        """
        # 点击停止测试
        self.click_img('stop_test_icon')

        # 点击确认上传
        self.click_img('confirm_sure')

        # 停止测试, 拼接要点击的图片名称
        self.stop_app_name = self.app_name + "_selected"
        self.click_img(self.stop_app_name)
        self.click_img("stop_test_label")
        self.click_img('select_test_app')


if __name__ == '__main__':
    # perfDogUtils = PerfDogUtils()
    # perfDogUtils.start_test()
    pass
